﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Gx.Common
{
    public class EnumHelper
    {
        /// <summary>
        /// 根据枚举key得到枚举value
        /// </summary>
        /// <param name="dataType"></param>
        /// <returns></returns>
        public static int GetDataTypeValue<T>(string enumName)
        {
            return (int)Enum.Parse(typeof(T), enumName);
        }


        /// <summary>
        /// 根据枚举value enum=1 这个1 得到描述信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="enumValue"></param>
        /// <returns></returns>
        public static string GetDataTypeDescription<T>(int enumValue)
        {
            string enumName = Enum.GetName(typeof(T), enumValue);
            return GetDataTypeDescription<T>(enumName);
        }

        /// <summary>
        /// 根据枚举key得到枚举注释
        /// </summary>
        /// <param name="enumName"></param>
        /// <returns></returns>
        public static string GetDataTypeDescription<T>(string enumName)
        {
            var type = typeof(T);
            if(string.IsNullOrWhiteSpace(enumName)) return string.Empty;
            var memInfo = type.GetMember(enumName);
            var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
            var description = ((DescriptionAttribute)attributes[0]).Description;
            return description;
        }
         

        /// <summary>
        /// 将枚举转换成字典
        /// </summary>
        /// <typeparam name="TEnum"></typeparam>
        /// <returns></returns>
        public static Dictionary<string, int> GetDic<TEnum>()
        {
            Dictionary<string, int> dic = new Dictionary<string, int>();
            Type t = typeof(TEnum);
            var arr = Enum.GetValues(t);
            foreach (var item in arr)
            {
                dic.Add(item.ToString(), (int)item);
            }

            return dic;
        }

        /// <summary>
        /// 获取枚举列表，值为枚举值，描述为枚举描述
        /// </summary>
        /// <typeparam name="TEnum"></typeparam>
        /// <returns></returns>
        public static List<EnumEntity> GetEnumList<TEnum>()
        {
            List<EnumEntity> list = new List<EnumEntity>();
            Type t = typeof(TEnum);
            var arr = Enum.GetValues(t);
            foreach (var item in arr)
            {
                EnumEntity entity = new EnumEntity();
                entity.Value = (int)item;
                entity.Description = GetDataTypeDescription<TEnum>(entity.Value);
                list.Add(entity);
            }

            return list;
        }
    }

    public class EnumEntity
    {
        public int Value { get; set; }
        public string Description { get; set; }
    }
}
